﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;

namespace MS.InformationManagement.BLL.DeliveryForms
{
    public class CreateDeliveryFormCommand : IBaseCommand
    {

        #region Fields

        Planilla _deliveryFormEntity;
        int _newDeliveryFormId;

        #endregion

        #region Constructors

        public CreateDeliveryFormCommand(Planilla deliveryFormEntity)
        {
            _deliveryFormEntity = deliveryFormEntity;
        }

        #endregion

        #region Implemented Command Methods

        public void Execute()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                attachEntities(dc,_deliveryFormEntity.Envios);
                attachEntities(dc, _deliveryFormEntity.EnvioPlanilla);
                dc.PlanillasEnvio.InsertOnSubmit(_deliveryFormEntity);
                dc.SubmitChanges();
                _newDeliveryFormId = _deliveryFormEntity.Id.Value;
            }

        }

        public void Undo()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var deliveryFormEntity = (from item in dc.PlanillasEnvio
                                          where item.Id == _newDeliveryFormId
                                          select item).FirstOrDefault();
                dc.PlanillasEnvio.DeleteOnSubmit(deliveryFormEntity);
                dc.SubmitChanges();
            }
        }

        #endregion

        #region private methods

        private void attachEntities(DCDocumentCenterDataContext dataContext, EntitySet<EnvíoDeCorrespondencia> deliveries)
        { 
            foreach(var delivery in deliveries)
            {
                dataContext.EnviosDeCorreo.Attach(delivery);
            }
        }

        private void attachEntities(DCDocumentCenterDataContext dataContext, MedioDeEnvio delivery)
        {
                dataContext.MediosDeEnvio.Attach(delivery);
        }

        #endregion
    }
}
